<?php
/**
 * @author Administrator
 * @date 2022/10/20 19:49
 * @desciption:
 */

namespace JsonApi\Controllers;

use App\GraphQL\User;
use App\GraphQL\UserType;
use GraphQL\GraphQL;
use GraphQL\Language\Parser;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use Illuminate\Support\Facades\DB;
use JsonApi\Fields;

class Build
{
    public function Query(){
        $rawInput = file_get_contents('php://input');
        $input = json_decode($rawInput, true);
        $query = $input['query'];
        $rootValue = ['prefix' => 'You said: '];
        $variableValues = isset($input['variables']) ? $input['variables'] : null;
        $result = $this->exec($query,$rootValue,null,$variableValues);

        header("Content-Type:application/json;charset=utf-8");
        echo json_encode($result);exit;
    }

    /**
     * @return ObjectType
     */
    private function getQueryType(){
        $queryType = new ObjectType([
            "name"          => "Query",
            "description"   => "",
            "fields"        => Fields::getAll()
        ]);
        return $queryType;
    }

    private function exec(
        $source,
        $rootValue = null,
        $context = null,
        $variableValues = null,
        $operationName = null,
        callable $fieldResolver = null,
        array $validationRules = null
    ){
        $schema = new Schema(["query" => $this->getQueryType()]);

        try {
            $result = GraphQL::executeQuery(
                $schema,
                $source,
                $rootValue,
                $context,
                $variableValues,
                $operationName,
                $fieldResolver,
                $validationRules
            );
            $output = $result->toArray();
        }catch (\Throwable $e){
            $output = [
                'errors' => [
                    [
                        'message' => $e->getMessage()
                    ]
                ]
            ];
        }
        return $output;
    }
}